using System.IO;
using System.Security.Principal;
using Microsoft.Win32;
using UnityEngine;

public class AutoStartMgr : Singleton<AutoStartMgr>
{
    // 自启动注册表路径
    private const string RUN_KEY = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run";
    
    /// <summary>
    /// 设置自启动状态
    /// </summary>
    public void SetAutoStart(bool enabled)
    {
        if (Application.isEditor)
        {
            return;
        }
        // 获取当前程序路径
        string appPath = Path.GetFullPath(Application.dataPath.Replace("_Data", ".exe")).Replace('/', Path.DirectorySeparatorChar); // 适用于打包后的exe
        // 编辑器模式下特殊处理
        if (Application.isEditor) appPath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;

        using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RUN_KEY, true))
        {
            if (enabled)
            {
                // 添加注册表项
                key.SetValue(Application.productName, $"\"{appPath}\"");
            }
            else
            {
                // 删除注册表项
                if (key.GetValue(Application.productName) != null)
                {
                    key.DeleteValue(Application.productName);
                }
            }
        }
    }

    /// <summary>
    /// 检查自启动状态
    /// </summary>
    public bool IsAutoStartEnabled()
    {
        using (RegistryKey key = Registry.CurrentUser.OpenSubKey(RUN_KEY, false))
        {
            return key.GetValue(Application.productName) != null;
        }
    }

    public bool IsAdministrator()
    {
        WindowsIdentity identity = WindowsIdentity.GetCurrent();
        WindowsPrincipal principal = new WindowsPrincipal(identity);
        return principal.IsInRole(WindowsBuiltInRole.Administrator);
    }
}